import conn_port from "./conn_port";
import { createResp, make_empty, make_req, TYPE_PING, TYPE_PONG, TYPE_SIMPLE_REQ, TYPE_SIMPLE_RES } from "./dispatcher"

let globalSeq = 0;

function get_seq() {
    let seq = globalSeq;
    globalSeq += 1;
    if (globalSeq > 255) {
        globalSeq = 0;
    }
    return seq;
}

export const CMD_OTA_START = 1;
export const CMD_OTA_TRANSLATE = 2;
export const CMD_OTA_COMPLETE = 3;
export const CMD_STATUS = 4;
export const CMD_LOG = 5;

export default {

    async ping() {
        let seq = get_seq();
        const promise = createResp(TYPE_PONG, seq, 500, "PONG超时");
        await conn_port.write( make_empty(TYPE_PING, seq) )
        await promise;
    },

    async simpleReq<T>(cmd: number, value: T) {
        let seq = get_seq();
        const promise = createResp(TYPE_SIMPLE_RES, seq, 500, "simple res超时");
        await conn_port.write( make_req(TYPE_SIMPLE_REQ, seq, cmd, value) );
        const res = await promise;
        res.assert();
    }

}
